package cn.lili.modules.grab.dingdong.service;

import cn.lili.common.exception.ServiceException;
import cn.lili.modules.grab.dingdong.utils.AESUtil;
import cn.lili.modules.grab.dingdong.utils.HttpClientUtil;
import cn.lili.modules.grab.dingdong.utils.RSAUtil;
import cn.lili.modules.grab.dingdong.base.BaseResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;

@Slf4j
public abstract class DingdongAbsService {

    /**
     * 发送post请求
     *
     * @param url          请求链接
     * @param dingdongBody 请求内容
     * @param publicKey    公钥
     */
    public BaseResult post(String url, String dingdongBody, String publicKey) {
        log.info("post-url---{}",url);
        log.info("post-dingdongBody---{}",dingdongBody);
        log.info("post-publicKey---{}",publicKey);
        String response = HttpClientUtil.post(url, dingdongBody);
        String result = StringEscapeUtils.unescapeJava(response);
        //"返回结果==="+result
        JSONObject resJson = JSON.parseObject(result);

        //如果返回不等于200，直接报错,并打印报错日志
        if (!"200".equals(resJson.getString("status"))) {
            log.error(resJson.getString("msg"));
            //返回结果组装
            return BaseResult.builder()
                    .status(resJson.getString("status"))
                    .msg(resJson.getString("msg"))
                    .build();
        }

        String responseEncryptedLock = resJson.get("lock").toString();
        String responseEncryptedContent = resJson.get("content").toString();
        String responseContent;

        try {
            String resonpseLock = RSAUtil.pubDecrypt(responseEncryptedLock, publicKey);
            responseContent = AESUtil.decrypt(responseEncryptedContent, resonpseLock);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //返回结果组装
        return BaseResult.builder()
                .status(resJson.getString("status"))
                .msg(resJson.getString("msg"))
                .content(responseContent)
                .build();
    }
}
